<template>
  <div>
    <!-- 分配权限的工作 -->
    <el-tree
      ref="tree"
      :data="listTree"
      :props="{label :'name'}"
      :show-checkbox="true"
      :default-expand-all="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="addFn">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listTree: [] // 存储权限数据
    }
  },
  mounted() {
    // 调用接口,获取所有的权限点数据
    this.loadlist()
    // 调用接口,获取到当前角色已有的权限点数据
    this.loadId()
  },
  methods: {
    async loadId() {
      const res = await getRoleDetail(this.roleId)
      console.log('获取到当前角色已有的权限点数据', res.data.permIds)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    async loadlist() {
      const res = await getPermissionList()
      console.log('获取所有的权限点数据', res)
      this.listTree = tranListToTreeData(res.data)
    },
    closeDialog() {
      // 1.  通知父组件关闭弹层
      this.$emit('false-l')
      // 2.清空当前选择
      this.$refs.tree.setCheckedKeys([])
    },
    // 通知父组件关闭弹层
    async addFn() {
    //   this.listTree = []
      // 当前选中的节点数组
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPerm({
        id: this.roleId,
        permIds
      })
      this.$message.success('保存角色的权限成功')
      this.closeDialog()
    }
  }
}
</script>

<style>

</style>
